import siteInfo from '../siteinfo.js';
import $util from "@/utils/index.js"
import $store from "@/store/index.js"
class Msg {
	limit = 0;
	localSocket = null;
	timeoutObj = null;
	watcherList = [];
	isLogin = false;
	lockReconnect = false;
	reconnectFail = false;
	constructor({
		url,
		timeout = 30000,
		reconnectTime = 10000,
		maxLimit = 5
	} = {}) {
		this.url = url;
		this.timeout = timeout;
		this.reconnectTime = reconnectTime;
		this.maxLimit = maxLimit;
	}
	async connect(param) {
		let that = this;
		let {
			url
		} = that

		let {
			uniacid
		} = siteInfo

		url = $util.getUrlToStr(`${url}`, param) + `&uniacid=${uniacid}&action=mOnOpenMsg`
		that.localSocket = uni.connectSocket({
			url,
			forceNew: true,
			complete: (res) => {}
		})
		that.localSocket.onOpen((res) => {
			console.log("=====onOpen", 'io_msg_status', res)
			uni.setStorageSync('io_msg_status', 1)
			that.sendMessage({
				action: 'enterRoom',
				data: param
			})
			that.reset().start()
		})
		that.localSocket.onClose((res) => {
			console.log("=====onClose", 'io_msg_status', res)
			uni.setStorageSync('io_msg_status', 2)
		})
		that.localSocket.onError((res) => {
			console.log("=====onError", 'io_msg_status', res)
			that.reconnect(param)
		})
		// 收到消息
		that.localSocket.onMessage((res) => {
			that.getSocketMsg(JSON.parse(res.data))
		})
		return that;
	}
	// 关闭
	async close() {
		this.localSocket.close()
	}
	// 重连
	reconnect(param) {
		let that = this;
		if (that.lockReconnect) return;
		that.lockReconnect = true;
		clearTimeout(that.timer);
		let pages = getCurrentPages()
		let len = pages.length
		let prePage = ''
		let curPage = ''
		if (len > 0) {
			curPage = pages[pages.length - 1].route
		}
		console.log(`重连--${curPage}`)
		if (curPage != 'im/pages/detail') return

		//10秒钟触发一次，避免太频繁
		that.timer = setTimeout(() => {
			that.limit++
			that.connect(param);
			that.lockReconnect = false;
			// if (that.limit < that.maxLimit) {
			// 	that.limit++
			// 	that.connect(param);
			// 	that.lockReconnect = false;
			// } else {
			// 	that.limit = 0;
			// 	that.reconnectFail = true;
			// 	that.lockReconnect = false;
			// }
		}, this.reconnectTime)
	}
	clearConnect() {
		let that = this;
		that.lockReconnect = true;
		if (that.timer) clearTimeout(that.timer);
	}
	reset() {
		if (this.timeoutObj) clearInterval(this.timeoutObj);
		this.limit = 0;
		return this;
	}
	start() {
		let that = this;
		//每隔30秒发送一次暗号
		that.timeoutObj = setInterval(() => {
			that.sendMessage({
				action: 'checkWs',
				data: {
					check: '78346+SJDHFA.longbing'
				}
			})
		}, that.timeout);
	}
	//收到消息
	getSocketMsg(res) {
		let that = this;
		let {
			status,
			message,
			action,
			data
		} = res
		that.publish(action, data);
	}
	//发送消息
	sendMessage(param) {
		let that = this;
		let {
			uniacid
		} = siteInfo;
		let token = uni.getStorageSync('autograph')
		param.data = Object.assign({}, param.data, {
			uniacid,
			token,
		})
		param = JSON.stringify(param)
		let readyState = that.localSocket.readyState
		if (readyState == 1) {
			return new Promise((resolve, reject) => {
				that.localSocket.send({
					data: param,
					success: function(res) {
						resolve(res)
					},
					fail: function(e) {
						reject(e)
					}
				})
			})
		} else {
			return {
				errMsg: readyState
			}
		}
	}
	// 订阅
	subscribe(key, fn) {
		//订阅的时候如果断线了,就重连
		if (!this.watcherList[key]) {
			this.watcherList[key] = [];
		}
		this.watcherList[key].push(fn);
	}
	// 发布
	publish() {
		let arg = arguments;
		let key = [].shift.call(arg);
		let fns = this.watcherList[key];
		if (!fns || fns.length <= 0) return false;
		for (var i = 0, len = fns.length; i < len; i++) {
			fns[i].apply(this, arg);
		}
	}
	// 取消订阅
	unSubscribe(key) {
		let fns = this.watcherList[key];
		if (!fns || fns.length <= 0) return false;
		delete this.watcherList[key];
	}
}

export default Msg;